import { createRouter, createWebHistory } from 'vue-router'
import store from '@/store'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('@/views/Home.vue')
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/auth/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/auth/Register.vue')
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('@/views/Profile.vue'),
    meta: {
        requiresAuth: true
    }
  },
  {
    path: '/products/manage',
    name: 'ProductManage',
    component: () => import('@/views/products/Manage.vue'),
    meta: {
        requiresAuth: true
    }
  },
  {
    path: '/cart',
    name: 'Cart',
    component: () => import('@/views/Cart.vue')
  },
  {
    path: '/favorites',
    name: 'Favorites',
    component: () => import('@/views/favorites/FavoritesView.vue'),
    meta: {
        requiresAuth: true
    }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach(async (to, from, next) => {
    const isLoggedIn = store.getters['user/isLoggedIn']
    
    if (to.matched.some(record => record.meta.requiresAuth)) {
        if (!isLoggedIn) {
            next({
                path: '/login',
                query: { redirect: to.fullPath }
            })
        } else {
            if (!store.getters['user/userInfo']) {
                try {
                    await store.dispatch('user/getUserInfo')
                } catch (error) {
                    next('/login')
                    return
                }
            }
            next()
        }
    } else {
        next()
    }
})

export default router
